package com.celesea.workflow.core.service;

import com.celesea.framework.service.AbstractBaseService;
import com.celesea.framework.util.CollectionKit;
import com.celesea.framework.util.EnvUtil;
import com.celesea.workflow.core.dao.WorkflowNodeDao;
import com.celesea.workflow.core.entity.WorkflowNode;
import com.celesea.workflow.core.vo.WorkflowDefineVo;
import com.celesea.workflow.core.vo.WorkflowNodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JackYuan
 * @create 2017-11-28 12:53
 */
@Service
public class WorkflowNodeServiceImpl extends AbstractBaseService<WorkflowNode> implements WorkflowNodeService {

    @Autowired
    private WorkflowNodeDao workflowNodeDao;

    @Autowired
    private WorkflowNodeActionService workflowNodeActionService;

    @Autowired
    private WorkflowNodePermissionService workflowNodePermissionService;

    @Override
    public int insertByWorkflowDefine(WorkflowDefineVo define) {
        if (CollectionKit.isEmpty(define.getNodes())) {
            return 0;
        }
        List<WorkflowNodeVo> nodeVos = define.getNodes();
        List<WorkflowNode> nodes = nodeVos.stream().map(item -> {
            generatPk(item);
            return item.toEntity();
        }).collect(Collectors.toList());
        int result = super.insertList(nodes);

        nodeVos.stream().forEach(item -> {
            // 保存节点动作
            item.initActionRelation(actions ->
                    workflowNodeActionService.insertList(actions));
            // 保存节点权限
            item.initPermissionRelation(permissions ->
                    workflowNodePermissionService.insertList(permissions));
        });
        return result;
    }

    @Override
    public int doDeleteByDefine(String id) {
        Example example = new Example(WorkflowNode.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("tenantId", EnvUtil.getTenantId())
                .andEqualTo("wfId", id);
        workflowNodeActionService.doDeleteByDefine(id);
        workflowNodePermissionService.doDeleteByDefine(id);
        return workflowNodeDao.deleteByExample(example);
    }
}
